import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AIAssistantDialog extends JDialog {
    private AIAssistant aiAssistant;
    private JTextArea inputArea;
    private JTextArea outputArea;
    private JTextField apiKeyField;
    private JComboBox<String> functionCombo;
    private JButton generateButton;
    private JButton useResultButton;
    private JButton cancelButton;
    private String result;

    public AIAssistantDialog(JFrame parent, AIAssistant aiAssistant) {
        super(parent, "AI写作助手", true);
        this.aiAssistant = aiAssistant;

        initializeComponents();
        setupLayout();
        setupEventListeners();

        setSize(800, 600);
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    private void initializeComponents() {
        // API Key输入框（隐藏，因为已在代码中配置）
        apiKeyField = new JTextField(20);
        apiKeyField.setText("API Key已配置");
        apiKeyField.setEditable(false);
        apiKeyField.setVisible(false);

        // 功能选择下拉框
        String[] functions = {
                "自定义提示",
                "改进文字",
                "总结内容",
                "扩展内容",
                "生成标题",
                "语法检查",
                "翻译成英文",
                "翻译成中文"
        };
        functionCombo = new JComboBox<>(functions);

        // 输入文本区域
        inputArea = new JTextArea(8, 40);
        inputArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        inputArea.setLineWrap(true);
        inputArea.setWrapStyleWord(true);
        inputArea.setBorder(new EmptyBorder(10, 10, 10, 10));
        inputArea.setBackground(new Color(248, 249, 250));

        // 输出文本区域
        outputArea = new JTextArea(8, 40);
        outputArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        outputArea.setLineWrap(true);
        outputArea.setWrapStyleWord(true);
        outputArea.setBorder(new EmptyBorder(10, 10, 10, 10));
        outputArea.setBackground(new Color(248, 249, 250));
        outputArea.setEditable(false);

        // 按钮
        generateButton = new JButton("生成内容");
        generateButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        generateButton.setBackground(new Color(0, 123, 255));
        generateButton.setForeground(Color.WHITE);
        generateButton.setFocusPainted(false);
        generateButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        useResultButton = new JButton("使用结果");
        useResultButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        useResultButton.setBackground(new Color(40, 167, 69));
        useResultButton.setForeground(Color.WHITE);
        useResultButton.setFocusPainted(false);
        useResultButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        useResultButton.setEnabled(false);

        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        cancelButton.setBackground(new Color(108, 117, 125));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setFocusPainted(false);
        cancelButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部面板 - 功能选择
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(new EmptyBorder(15, 15, 10, 15));

        JPanel functionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        functionPanel.add(new JLabel("AI功能:"));
        functionPanel.add(functionCombo);

        topPanel.add(functionPanel, BorderLayout.CENTER);

        // 中间面板 - 输入输出区域
        JPanel centerPanel = new JPanel(new GridLayout(2, 1, 10, 10));
        centerPanel.setBorder(new EmptyBorder(10, 15, 10, 15));

        // 输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(new JLabel("输入内容:"), BorderLayout.NORTH);
        JScrollPane inputScroll = new JScrollPane(inputArea);
        inputScroll.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(""),
                BorderFactory.createEmptyBorder()));
        inputPanel.add(inputScroll, BorderLayout.CENTER);

        // 输出区域
        JPanel outputPanel = new JPanel(new BorderLayout());
        outputPanel.add(new JLabel("AI生成结果:"), BorderLayout.NORTH);
        JScrollPane outputScroll = new JScrollPane(outputArea);
        outputScroll.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(""),
                BorderFactory.createEmptyBorder()));
        outputPanel.add(outputScroll, BorderLayout.CENTER);

        centerPanel.add(inputPanel);
        centerPanel.add(outputPanel);

        // 底部面板 - 按钮
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 15));
        bottomPanel.add(generateButton);
        bottomPanel.add(useResultButton);
        bottomPanel.add(cancelButton);

        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void setupEventListeners() {
        // 生成按钮事件
        generateButton.addActionListener(e -> generateContent());

        // 使用结果按钮事件
        useResultButton.addActionListener(e -> {
            result = outputArea.getText();
            dispose();
        });

        // 取消按钮事件
        cancelButton.addActionListener(e -> {
            result = null;
            dispose();
        });

        // 功能选择变化事件
        functionCombo.addActionListener(e -> updateInputPlaceholder());

        // 初始化占位符
        updateInputPlaceholder();
    }

    private void updateInputPlaceholder() {
        String selectedFunction = (String) functionCombo.getSelectedItem();
        final String placeholder = getPlaceholderText(selectedFunction);

        if (inputArea.getText().isEmpty() || inputArea.getText().startsWith("请输入")) {
            inputArea.setText(placeholder);
            inputArea.setForeground(Color.GRAY);
        }

        // 移除之前的焦点监听器
        java.awt.event.FocusListener[] listeners = inputArea.getFocusListeners();
        for (java.awt.event.FocusListener listener : listeners) {
            inputArea.removeFocusListener(listener);
        }

        // 添加焦点监听器处理占位符
        inputArea.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                if (inputArea.getText().equals(placeholder)) {
                    inputArea.setText("");
                    inputArea.setForeground(Color.BLACK);
                }
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                if (inputArea.getText().isEmpty()) {
                    inputArea.setText(placeholder);
                    inputArea.setForeground(Color.GRAY);
                }
            }
        });
    }

    private String getPlaceholderText(String selectedFunction) {
        switch (selectedFunction) {
            case "自定义提示":
                return "请输入您的自定义提示词和需要处理的文本...";
            case "改进文字":
                return "请输入需要改进的文字...";
            case "总结内容":
                return "请输入需要总结的内容...";
            case "扩展内容":
                return "请输入需要扩展的内容...";
            case "生成标题":
                return "请输入文章内容，AI将为您生成标题...";
            case "语法检查":
                return "请输入需要检查语法的文字...";
            case "翻译成英文":
                return "请输入需要翻译成英文的中文内容...";
            case "翻译成中文":
                return "请输入需要翻译成中文的英文内容...";
            default:
                return "请输入内容...";
        }
    }

    private void generateContent() {
        String input = inputArea.getText().trim();
        String selectedFunction = (String) functionCombo.getSelectedItem();

        // 检查输入是否为空或占位符
        if (input.isEmpty() || input.startsWith("请输入")) {
            JOptionPane.showMessageDialog(this, "请先输入内容", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 检查API Key
        if (!aiAssistant.isConfigured()) {
            JOptionPane.showMessageDialog(this, "API Key未配置，请在代码中填入您的DeepSeek API Key", "错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 禁用按钮，显示加载状态
        generateButton.setEnabled(false);
        generateButton.setText("生成中...");
        outputArea.setText("AI正在生成内容，请稍候...");

        // 在后台线程中调用AI
        SwingUtilities.invokeLater(() -> {
            try {
                String result = generateAIContent(selectedFunction, input);
                outputArea.setText(result);
                useResultButton.setEnabled(true);
            } catch (Exception e) {
                outputArea.setText("生成失败: " + e.getMessage());
                e.printStackTrace();
            } finally {
                generateButton.setEnabled(true);
                generateButton.setText("生成内容");
            }
        });
    }

    private String generateAIContent(String function, String input) {
        switch (function) {
            case "自定义提示":
                return aiAssistant.generateContent(input, "");
            case "改进文字":
                return aiAssistant.improveText(input);
            case "总结内容":
                return aiAssistant.summarizeText(input);
            case "扩展内容":
                return aiAssistant.expandText(input);
            case "生成标题":
                return aiAssistant.generateTitle(input);
            case "语法检查":
                return aiAssistant.checkGrammar(input);
            case "翻译成英文":
                return aiAssistant.translateText(input, "英文");
            case "翻译成中文":
                return aiAssistant.translateText(input, "中文");
            default:
                return aiAssistant.generateContent(input, "");
        }
    }

    public String getResult() {
        return result;
    }
}